Page({
  data: {
    addresses: []
  },

  onLoad() {
    // 验证登录状态
    const userData = wx.getStorageSync('userData');
    if (!userData) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.navigateBack();
      return;
    }
    this.loadAddresses();
  },

  // 加载地址列表
  loadAddresses() {
    const addresses = wx.getStorageSync('userAddresses') || [];
    this.setData({ addresses });
  },

  // 返回上一页
  goback() {
    wx.navigateBack();
  },

  // 添加地址（简化版，实际需跳转表单页）
  addAddress() {
    const newAddress = {
      id: Date.now(),
      name: '请输入收货人',
      phone: '请输入手机号',
      address: '请输入详细地址',
      isDefault: this.data.addresses.length === 0
    };
    const addresses = [...this.data.addresses, newAddress];
    wx.setStorageSync('userAddresses', addresses);
    this.setData({ addresses });
    wx.showToast({ title: '地址已添加，可点击编辑完善' });
  },

  // 编辑地址（修复：提前保存 this 到 that，避免绑定问题）
  editAddress(e) {
    const id = e.currentTarget.dataset.id;
    const addresses = this.data.addresses;
    const index = addresses.findIndex(item => item.id === id);
    if (index === -1) return;

    // 关键：提前保存页面实例的 this 到 that
    const that = this;
    // 模拟编辑：弹出输入框修改收货人
    wx.prompt({
      title: '编辑收货人',
      value: addresses[index].name,
      success(res) {
        if (res.confirm) {
          addresses[index].name = res.content.trim();
          wx.setStorageSync('userAddresses', addresses);
          // 用 that 调用 setData，确保指向页面实例
          that.setData({ addresses });
        }
      }
      // 移除 .bind(this)，避免环境兼容问题
    });
  },

  // 删除地址（无需修改，已有正确的 that 保存）
  deleteAddress(e) {
    const that = this;
    const id = e.currentTarget.dataset.id;
    const addresses = that.data.addresses;
    const isDefault = addresses.find(item => item.id === id)?.isDefault;

    wx.showModal({
      title: '确认删除',
      content: '删除后不可恢复，是否继续？',
      success(res) {
        if (res.confirm) {
          const newAddresses = addresses.filter(item => item.id !== id);
          // 若删除默认地址，将第一个设为默认
          if (isDefault && newAddresses.length > 0) {
            newAddresses[0].isDefault = true;
          }
          wx.setStorageSync('userAddresses', newAddresses);
          that.setData({ addresses: newAddresses });
          wx.showToast({ title: '地址已删除' });
        }
      }
    });
  }
});